new Vue({
    el: '#app',
    data: {
        addresses: [], // 地址列表
        showModal: false, // 控制新建/编辑地址模态框显示
        editMode: false, // 判断当前是编辑模式还是新建模式
        currentAddress: { // 当前正在编辑或新建的地址数据
            id: '',
            recipient: '',
            phone: '',
            region: '',
            address: '',
            detail: '',
            isDefault: false,
            province: '',
            city: '',
            district: '',
            countryCode: '+86'
        },
        provinces: [], // 省份列表数据
        cities: [], // 城市列表数据
        districts: [], // 区县列表数据
        orderItems: [], // 订单商品列表
        selectedAddress: null, // 用户选中的地址
        orderNotes: '', // 订单备注内容
        showCountdown: false, // 控制倒计时显示
        countdown: 300, // 倒计时秒数
        timer: null, // 存储定时器ID
        currentOrderId: null,// 当前订单ID
        alipayForm: null,// 支付宝支付表单
        orderNo: null,// 订单编号
        selectedIndex: -1, // 当前选中地址的索引
    },
    computed: {
        orderTotalAmount() {
            return this.orderItems.reduce((total, item) => total + (item.commoditySalePrice * item.commodityNum), 0).toFixed(2);
        },
        // 格式化倒计时显示
        countdownDisplay() {
            const minutes = Math.floor(this.countdown / 60);
            const seconds = this.countdown % 60;
            return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
    },
    methods: {
        // 获取用户ID
        getUserIdFromUrl() {
           return localStorage.getItem('userId');
        },

        // 获取地址列表
        fetchAddresses() {
            // const userId = this.getUserIdFromUrl();
            $.ajax({
                url: `http://localhost:8080/address/findAllAddress`,
                type: 'POST',
                dataType: 'json',
                data: { userId: localStorage.getItem('userId') },
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (response) => {
                    if (response.code === 200 && Array.isArray(response.data)) {
                        this.addresses = response.data;
                        // 处理默认地址
                        let defaultAddrIndex = -1;
                        // 遍历地址列表，处理默认地址
                        let processedAddresses = response.data.map((addr, index) => {
                            this.$set(addr, 'isDefault', !!addr.isDefault);

                            // 找到第一个默认地址的索引
                            if (addr.isDefault && defaultAddrIndex === -1) {
                                defaultAddrIndex = index;
                            }
                            return addr;
                        });

                        // 在前端处理：如果后端返回多个默认地址，只保留第一个的默认状态 (基于索引)
                        if (defaultAddrIndex !== -1) {
                            processedAddresses.forEach((addr, index) => {
                                if (index !== defaultAddrIndex) {
                                    this.$set(addr, 'isDefault', false); // 取消其他默认状态
                                }
                            });
                        }
                        this.addresses = processedAddresses;
                        // 如果没有地址，则将索引设置为-1
                        if (this.addresses.length > 0) {
                            this.selectedIndex = defaultAddrIndex !== -1 ? defaultAddrIndex : 0;
                            this.selectedAddress = this.addresses[this.selectedIndex];
                        } else {
                            this.selectedIndex = -1;
                            this.selectedAddress = null;
                        }

                    } else {
                        this.addresses = [];
                        this.selectedAddress = null;
                        this.selectedIndex = -1;
                        alert('加载地址列表失败: ' + (response.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    this.addresses = [];
                }
            });
        },

         // 加载省份数据 (用于三级联动)
        loadProvinces() {
            $.ajax({
                url: "http://hmajax.itheima.net/api/province",
                type: 'GET',
                dataType: 'json',
                success: (result) => {
                    this.provinces = result.list;
                }
            });
        },

        // 省份选择改变时加载城市
        onProvinceChange() {
            this.currentAddress.city = '';
            this.currentAddress.district = '';
            this.cities = [];
            this.districts = [];
            if (this.currentAddress.province) {
                $.ajax({
                    url: "http://hmajax.itheima.net/api/city",
                    type: 'GET',
                    data: { pname: this.currentAddress.province },
                    dataType: 'json',
                    success: (result) => {
                        this.cities = result.list;
                    }
                });
            }
        },

        // 城市选择改变时加载区县
        onCityChange() {
            this.currentAddress.district = '';
            this.districts = [];
            if (this.currentAddress.province && this.currentAddress.city) {
                $.ajax({
                    url: "http://hmajax.itheima.net/api/area",
                    type: 'GET',
                    data: {
                        pname: this.currentAddress.province,
                        cname: this.currentAddress.city
                    },
                    dataType: 'json',
                    success: (result) => {
                        this.districts = result.list;
                    }
                });
            }
        },

        // 打开新建地址模态框
        openNewAddress() {
            // 重置currentAddress数据
            this.currentAddress = {
                id: '',
                recipient: '',
                phone: '',
                region: '',
                detail: '',
                isDefault: false,
                province: '',
                city: '',
                district: '',
                countryCode: '+86'
            };
            this.editMode = false;
            this.showModal = true;

            // 清空城市和区县下拉框数据
            this.cities = [];
            this.districts = [];
            // 确保省份下拉框加载了数据
            if (this.provinces.length === 0) {
                this.loadProvinces();
            }
        },

        // 打开编辑地址模态框并填充数据
        async editAddress(addr) {
            console.log('编辑地址:', addr);
            // 初始化编辑数据
            this.currentAddress = { ...addr };
            this.editMode = true; // 设置为编辑模式
            this.showModal = true;

            // 解析region字符串，填充省市区字段
            if (this.currentAddress.region) {
                const regionParts = this.currentAddress.region.split(' ');
                if (regionParts.length >= 1) this.currentAddress.province = regionParts[0];
                if (regionParts.length >= 2) this.currentAddress.city = regionParts[1];
                if (regionParts.length >= 3) this.currentAddress.district = regionParts[2];
            }
            console.log('当前地址:', this.currentAddress);

            // 根据已有的省份加载城市
            if (this.currentAddress.province) {
                $.ajax({
                    url: "http://hmajax.itheima.net/api/city",
                    type: 'GET',
                    data: { pname: this.currentAddress.province },
                    dataType: 'json',
                    success: (cityRes) => {
                        this.cities = cityRes.list;
                        // 根据已有的城市加载区县
                        if (this.currentAddress.city) {
                            $.ajax({
                                url: "http://hmajax.itheima.net/api/area",
                                type: 'GET',
                                data: { pname: this.currentAddress.province, cname: this.currentAddress.city },
                                dataType: 'json',
                                success: (districtRes) => {
                                    this.districts = districtRes.list;
                                }
                            });
                        } else {
                            this.districts = [];
                        }
                    }
                });
            } else {
                // 如果没有省份信息，清空城市和区县下拉框
                this.cities = [];
                this.districts = [];
            }
            // 确保省份下拉框加载了数据
            if (this.provinces.length === 0) {
                this.loadProvinces();
            }
        },      
        // 保存地址
        saveAddress() {
            const url = this.editMode ? '/updateAddress' : '/addAddress';
            const method = 'POST';

            // 组织要发送到后端的数据
            const addressData = {
                ...this.currentAddress,
                region: `${this.currentAddress.province || ''} ${this.currentAddress.city || ''} ${this.currentAddress.district || ''}`.trim(),
                userId: this.getUserIdFromUrl()
            };

            $.ajax({
                url: "http://localhost:8080/address" + url,
                type: method,
                contentType: 'application/json',
                data: JSON.stringify(addressData),
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                dataType: 'json',
                success: (res) => {
                    if (res.code === 200) {
                        alert(this.editMode ? '地址更新成功' : '新地址添加成功');
                        this.showModal = false;
                        this.fetchAddresses();
                    } else {
                        alert('操作失败：' + res.message);
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，保存失败', status, err);
                }
            });
        },

        // 获取订单详细信息，包括商品列表
        fetchOrderDetails() {
            const params = new URLSearchParams(window.location.search);
            const orderId = params.get('orderId');
            if (!orderId) {
                console.error('URL中缺少orderId参数');
                return;
            }

            $.ajax({
                url: `http://localhost:8080/order/findOrderById?orderId=${encodeURIComponent(orderId)}`,
                type: 'GET',
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        this.orderItems = res.data.commodityList;
                        this.orderNo = res.data.orderId;
                        this.orderItems.forEach(product => {
                            // 处理商品图片路径
                            if (product.commodityPicture && product.commodityPicture.length > 0) {
                                product.commodityPicture[0].commodityImageUrl = '/' + product.commodityPicture[0].commodityImageUrl.match(/photo[\\\\/].+$/)[0];
                            } else {
                                product.image = '/photo/default.jpg'; // 默认图片
                            }
                            console.log('商品图片路径:', product.commodityPicture[0].commodityImageUrl)
                        });
                    } else {
                        this.orderItems = [];
                        console.error('获取订单商品失败:', res);
                        alert('获取订单商品失败: ' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    this.orderItems = [];
                    console.error(status, error);
                    alert('网络错误，获取订单商品失败');
                }
            });
        },
        // 选择地址
        selectAddress(address, index) {
            // 如果点击的已经是当前选中的地址，不做处理
            if (this.selectedIndex === index) {
                return;
            }

            // 更新选中地址的索引和对象
            this.selectedIndex = index;
            this.selectedAddress = address;

            console.log('选中地址:', address);
        },
        // 设置默认地址
        setDefaultAddress(address) {
            // 先取消所有地址的默认状态
            if (address.isDefault) {
                return;
            }
            $.ajax({
                url: 'http://localhost:8080/address/setDefault',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ id: address.id, userId: localStorage.getItem('userId') }),
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        alert('默认地址设置成功');
                        this.fetchAddresses(); // 重新获取地址列表
                    } else {
                        alert('设置默认地址失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，设置默认地址失败');
                    console.error(status, error);
                }
            });
        },
        // 处理默认地址选择框变化
        onDefaultAddressChange(address) {
            if (address.isDefault) {
                this.setDefaultAddress(address);
            }
        },
        // 提交订单
        submitOrder() {
            if (!this.selectedAddress) {
                alert('请选择收货地址');
                return;
            }

            if (this.orderItems.length === 0) {
                alert('订单商品为空，无法提交订单');
                return;
            }

            // 获取当前时间并格式化为 YYYY-MM-DD HH:mm:ss
            const now = new Date();
            const createTime = now.getFullYear() + '-' +
                String(now.getMonth() + 1).padStart(2, '0') + '-' +
                String(now.getDate()).padStart(2, '0') + ' ' +
                String(now.getHours()).padStart(2, '0') + ':' +
                String(now.getMinutes()).padStart(2, '0') + ':' +
                String(now.getSeconds()).padStart(2, '0');

            // 准备提交订单的数据
            const orderData = {
                addressId: this.selectedAddress.id, // 选中的地址ID
                notes: this.orderNotes, // 添加订单备注
                createTime: createTime, // 添加创建时间
                items: this.orderItems.map(item => ({
                    productId: item.productId,
                    quantity: item.quantity
                }))
            };

            $.ajax({
                // 后端提交订单的接口
                url: 'http://localhost:8080/alipay/qrcode',
                type: 'POST',
                data: {
                    orderNo: this.orderNo,
                    amount: this.orderTotalAmount
                },
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        // 订单提交成功，生成支付二维码
                        this.alipayForm = res.data; // 获取支付宝支付表单
                        console.log('支付宝表单:', this.alipayForm);
                        this.$nextTick(() => {
                            const container = document.getElementById('alipay-container');
                            const form = container.querySelector('form'); // 在容器内查找表单
                            if (form) {
                                form.submit();
                            } else {
                                console.error('找不到 <form> 元素，请检查插入的内容是否为完整 HTML 表单');
                            }
                        });

                    } else {
                        alert('提交订单失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，提交订单失败');
                    console.error(status, error);
                }
            });
        },

        // 查询支付状态
        pollPaymentStatus(orderId) {
            // 检查当前页面是否仍显示支付相关内容，如果用户已离开此页，则停止查询
            const paymentContainer = document.querySelector('.payment-container');
            if (!paymentContainer || paymentContainer.style.display === 'none') {
                console.log('用户已离开支付页面，停止轮询。');
                return;
            }
            const checkStatus = () => {
                $.ajax({
                    url: `/api/payment/status?orderId=${orderId}`,
                    type: 'GET',
                    dataType: 'json',
                    headers: { 'token': `${localStorage.getItem('token') || ''}` },
                    success: (res) => {
                        if (res.code === 200) {
                            if (res.data.status === 'PAID') {
                                // 支付成功，清除定时器
                                this.stopCountdown();
                                // 支付成功，跳转到订单列表页面
                                alert('支付成功！');
                                window.location.href = `order.html?orderId=${orderId}`;
                            } else if (res.data.status === 'PENDING') {
                                // 继续查询
                                setTimeout(checkStatus, 3000);
                            } else {
                                alert('支付失败：' + (res.message || '未知错误'));
                                // 支付失败，可以隐藏支付区域，或显示失败信息
                                const paymentContainer = document.querySelector('.payment-container');
                                if (paymentContainer) paymentContainer.style.display = 'none';
                                this.stopCountdown(); // 停止倒计时
                            }
                        } else {
                            console.error('查询支付状态失败:', res);
                            // 继续轮询，或者根据错误类型决定是否停止
                            setTimeout(checkStatus, 3000);
                        }
                    },
                    error: (xhr, status, error) => {
                        console.error(status, error);
                        // 网络错误，继续轮询一段时间，或者停止
                        setTimeout(checkStatus, 3000);
                    }
                });
            };

            // 开始查询
            checkStatus();
        }
    },
    // 启动倒计时
    startCountdown() {
        this.countdown = 300; // 重置倒计时
        // 清除之前的定时器，避免重复启动
        if (this.timer) {
            clearInterval(this.timer);
        }
        this.timer = setInterval(() => {
            if (this.countdown > 0) {
                this.countdown--;
            } else {
                this.stopCountdown();
                // 倒计时结束隐藏支付区域，不在这里自动取消订单
                const paymentContainer = document.querySelector('.payment-container');
                if (paymentContainer) paymentContainer.style.display = 'none';
            }
        }, 1000); // 每秒更新
    },

    // 停止倒计时
    stopCountdown() {
        clearInterval(this.timer);
        this.timer = null;
        this.showCountdown = false; // 隐藏倒计时
    },

    created() {
        this.fetchAddresses();
        this.loadProvinces();
        this.fetchOrderDetails(); // 在页面加载时获取订单详情
    }
});